// INSE6260-ATM Simulator Project

/**
 * View package contains ATMS GUI.
 */
package com.inse6260.atms.view;

import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JLabel;

import com.inse6260.atms.controller.ATMSController;

/**
 *
 * @author dimitri.tiago
 */
public class Keypad extends javax.swing.JPanel
{
    // fields
    private JPanel currentScreenPanel;   // gui components
    private JButton[] buttons;

    private StringBuffer keyPadInput;   // key pad input

    private ATMSController atmsController;   // atms Screen

    /**
     * Default constructor initializes keypad GUI
     */
    public Keypad(ATMSController atmsController)
    {
        initComponents();

        // initialize fields
        keyPadInput     = new StringBuffer();
        this.atmsController = atmsController;
    }

    /**
     * Sets the current screen panel
     * @param currentScreenPanel current screen JPanel object
     */
    public void setCurrentScreenPanel(JPanel newCurrentScreenPanel)
    {
        currentScreenPanel = newCurrentScreenPanel;
    }

    /**
     * Returns current screen panel
     * @return current screen panel
     */
    public JPanel getCurrentSceenPanel()
    {
        return currentScreenPanel;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        Button1 = new javax.swing.JButton();
        Button2 = new javax.swing.JButton();
        Button3 = new javax.swing.JButton();
        Button4 = new javax.swing.JButton();
        Button5 = new javax.swing.JButton();
        Button6 = new javax.swing.JButton();
        Button7 = new javax.swing.JButton();
        Button8 = new javax.swing.JButton();
        Button9 = new javax.swing.JButton();
        Button0 = new javax.swing.JButton();
        OkButton = new javax.swing.JButton();
        CancelButton = new javax.swing.JButton();
        ClearButton = new javax.swing.JButton();

        Button1.setText("1");
        Button1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        Button2.setText("2");
        Button2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        Button3.setText("3");
        Button3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        Button4.setText("4");
        Button4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        Button5.setText("5");
        Button5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        Button6.setText("6");
        Button6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        Button7.setText("7");
        Button7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        Button8.setText("8");
        Button8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        Button9.setText("9");
        Button9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        Button0.setText("0");
        Button0.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        OkButton.setText("OK");
        OkButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        CancelButton.setText("CANCEL");
        CancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        ClearButton.setText("Clear");
        ClearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Keypad.this.actionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(31, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Button1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Button2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Button3))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(Button4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(Button5))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(Button0)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(Button7)
                                    .addGap(6, 6, 6)
                                    .addComponent(Button8))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(Button9)
                            .addComponent(Button6))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(CancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(OkButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(ClearButton, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(29, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Button1)
                    .addComponent(Button2)
                    .addComponent(Button3)
                    .addComponent(ClearButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Button4)
                    .addComponent(Button5)
                    .addComponent(Button6)
                    .addComponent(OkButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Button8)
                    .addComponent(Button7)
                    .addComponent(Button9)
                    .addComponent(CancelButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Button0)
                .addGap(25, 25, 25))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void actionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_actionPerformed

        if (evt.getActionCommand().equalsIgnoreCase("CLEAR"))
        {
            // clear keypad Input
            int kepadInputLength = keyPadInput.length();
            keyPadInput.delete(0, kepadInputLength);

            // if login panel
            if (currentScreenPanel instanceof LogInPanel)
            {
                LogInPanel logInPanel           = (LogInPanel) currentScreenPanel;
                JTextField cardField            = logInPanel.getCardTextField();
                JPasswordField passwordField    = logInPanel.getPasswordTextField();

                // determine which field we are processing
                if (passwordField.isVisible() == false)
                {
                    // update card input field
                    cardField.setText(keyPadInput.toString());
                }
                else
                {
                    // update password input field
                    passwordField.setText(keyPadInput.toString());
                }
            }

            if (currentScreenPanel instanceof AmountInputPanel)
            {
                // TODO: refactor into utility method
                AmountInputPanel amtInputPanel = (AmountInputPanel) currentScreenPanel;
                JTextField       amtInputField = amtInputPanel.getAmtInputField();

                amtInputField.setText(keyPadInput.toString());
            }
        }
        else if (evt.getActionCommand().equalsIgnoreCase("CANCEL"))
        {
            // request log in screen
            atmsController.showLogInPanel();
        }
        else if (evt.getActionCommand().equalsIgnoreCase("OK"))
        {
            // process ok
   
            // if log in screen is attched to keypad
            if (currentScreenPanel instanceof LogInPanel)
            {
                // handle card and password inputs

                // TODO: refactor into utility method
                LogInPanel logInPanel           = (LogInPanel) currentScreenPanel;
                JTextField cardField            = logInPanel.getCardTextField();
                JPasswordField passwordField    = logInPanel.getPasswordTextField();
                JLabel failureLabel             = logInPanel.getFailureReasonLabel();

                // process card number field (i.e. password field has not been shown)
                if (passwordField.isVisible() == false)
                {
                    // processing card input field

                    // local variables
                    String cardNumber = keyPadInput.toString();

                    // clear keypad Input
                    int keypadInputLength = keyPadInput.length();
                    keyPadInput.delete(0, keypadInputLength);

                    // validate that card number is not null
                    if ((cardNumber != null) && !(cardNumber.equalsIgnoreCase("")))
                    {
                        // validate card number exists at bank database
                        String cardNumberValidation = atmsController.inputCardNumber(cardNumber);  //TODO: handle null input
                        if (cardNumberValidation.equalsIgnoreCase("Success"))
                        {
                            // sucess. set acknowledged card number and disable field
                            cardField.setText(cardNumber);
                            cardField.setEnabled(false);    // TODO: card field should be always disabled.

                            // show password field
                            logInPanel.showPasswordField(true);

                            // update failure label
                            failureLabel.setText("");
                        }
                        else
                        {
                            // update failure label
                            failureLabel.setText(cardNumberValidation);

                            // update card input textfield
                            cardField.setText(keyPadInput.toString());
                        }
                    }
                }
                else
                {
                    // process password field (i.e. card number has been validated)

                    // show password input
                    String password = keyPadInput.toString();

                    // clear keypad Input
                    int keypadInputLength = keyPadInput.length();
                    keyPadInput.delete(0, keypadInputLength);

                    if ((password != null) && !(password.equalsIgnoreCase("")))
                    {
                        // validate password
                        String passwordValidation = atmsController.inputPassword(password);
                        if (passwordValidation.equalsIgnoreCase("Success"))
                        {
                            // sucess. set acknowledged card number and disable field
                            passwordField.setText(password);
                            passwordField.setEnabled(false);    // TODO: card field should be always disabled.

                            // transition to main menu panel.
                            atmsController.showATMSMainMenu();

                            // clear failure label
                            failureLabel.setText("");
                        }
                        else
                        {
                            // update failure label
                            failureLabel.setText(passwordValidation);

                            // update password input textfield
                            passwordField.setText(keyPadInput.toString());
                        }
                    }
                }
            }

            if (currentScreenPanel instanceof AmountInputPanel)
            {
                // capture input and transition to next panel

                // local variables
                String inputAmt = "0";

                // clear keypad Input
                int keypadInputLength = keyPadInput.length();
                keyPadInput.delete(0, keypadInputLength);

                // TODO: refactor into utility method
                AmountInputPanel amtInputPanel = (AmountInputPanel) currentScreenPanel;
                JTextField amtInputField       = amtInputPanel.getAmtInputField();

                inputAmt = amtInputField.getText();
                if ((inputAmt != null) && (!inputAmt.equalsIgnoreCase("0")) && (!inputAmt.equalsIgnoreCase("")))
                {
                    // handle withdrawal other input
                    if (atmsController.getCurrTransaction().equalsIgnoreCase("withdrawal"))
                    {
                        if ((Float.parseFloat(inputAmt) % 20) != 0)
                        {
                            amtInputPanel.setLabelText("please enter amount multiple of 20.");
                            amtInputField.setText("");
                        }
                        else
                        {
                            // request withdrawal
                            atmsController.requestWithdrawal(inputAmt);
                        }
                    }
                    else
                    {
                        // handle other inputs (deposit/transfer)

                        // set transaction parameter
                        atmsController.setCurrTransParams("amount", inputAmt);

                        // trasition to next panel
                        atmsController.showNextPanel();
                    }
                }
                else
                {
                    amtInputPanel.setLabelText("please enter an amount.");
                    amtInputField.setText("");
                }
            }
        }
        else
        {
            // get 0-9 input
            keyPadInput.append(evt.getActionCommand());

            if (currentScreenPanel instanceof LogInPanel)
            {
                LogInPanel logInPanel           = (LogInPanel) currentScreenPanel;
                JTextField cardField            = logInPanel.getCardTextField();
                JPasswordField passwordField    = logInPanel.getPasswordTextField();

                // determine which field we are processing
                if (passwordField.isVisible() == false)
                {
                    // show keypad input
                    cardField.setText(keyPadInput.toString());
                }
                else
                {
                    passwordField.setText(keyPadInput.toString());
                }
            }

            if (currentScreenPanel instanceof AmountInputPanel)
            {
                // TODO: refactor into utility method
                AmountInputPanel amtInputPanel = (AmountInputPanel) currentScreenPanel;
                JTextField       amtInputField = amtInputPanel.getAmtInputField();

                amtInputField.setText(keyPadInput.toString());
            }
        }
    }//GEN-LAST:event_actionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Button0;
    private javax.swing.JButton Button1;
    private javax.swing.JButton Button2;
    private javax.swing.JButton Button3;
    private javax.swing.JButton Button4;
    private javax.swing.JButton Button5;
    private javax.swing.JButton Button6;
    private javax.swing.JButton Button7;
    private javax.swing.JButton Button8;
    private javax.swing.JButton Button9;
    private javax.swing.JButton CancelButton;
    private javax.swing.JButton ClearButton;
    private javax.swing.JButton OkButton;
    // End of variables declaration//GEN-END:variables

}
